﻿using DataModels.Dto;
using DataModels.Entities.Base;
using DataModels.Entities.House;
using Dm;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using SqlSugar;
using Utils;
using static DataModels.Enums.GeneralEnum;

namespace Services
{
    public class BaseService(SqlSugarClient db)
    {
        protected readonly SqlSugarClient db = db;
        protected readonly IConfiguration? configuration = null;
        protected ResponseModel res = new();

        // 构造函数2：需要数据库和配置
        public BaseService(SqlSugarClient db, IConfiguration configuration)
            : this(db)
        {
            this.configuration = configuration;
        }
        // 服务定位器 - 用于静态访问服务容器
        public static class ServiceLocator
        {
            private static IServiceProvider _provider;

            public static void Initialize(IServiceProvider provider)
            {
                _provider = provider;
            }

            public static T GetService<T>()
            {
                return _provider.GetRequiredService<T>();
            }
        }

        /// <summary>
        /// 当前用户的四格id
        /// </summary>
        protected int GetCustIdBySIGE()
        {
            var customer = db.Queryable<Customer>().Where(c => c.UUID == UserUUID).First();
            return customer?.CustId ?? 0;

        }

        /// <summary>
        /// 当前用户的所有四格id
        /// </summary>
        protected List<int?> GetCustIdListBySIGE()
        {
            var customer = db.Queryable<Customer>().Where(c => c.UUID == UserUUID).First();
            if(customer==null)
                return new List<int?>();

           return db.Queryable<Customer>().Where(c => c.Tel1 == customer.Tel1).Select(c=>c.CustId).ToList();

        }

        /// <summary>
        /// 通过四格Id获取项目UUID
        /// </summary>
        /// <param name="p_id"></param>
        /// <returns></returns>
        protected string GetProjectUUIDBySIGE(int p_id)
        {
            var projects = db.Queryable<Projects>().Where(c => c.CommunityId == p_id.ToString()).First();
            return projects.UUID.ToString();
        }

        /// <summary>
        /// 根据项目UUID获取四格ID
        /// </summary>
        /// <param name="projectsUUID"></param>
        /// <returns></returns>
        protected string GetOrganIdBySIGE(Guid projectsUUID)
        {
            var projects = db.Queryable<Projects>().Where(c => c.UUID == projectsUUID).First();
            return projects.CommunityId;
        }

        /// <summary>
        /// 根据房屋UUID获取四格房屋ID
        /// </summary>
        /// <param name="houseUUID"></param>
        /// <returns></returns>
        protected int GetHouseIdBySIGE(Guid houseUUID)
        {
            var house = db.Queryable<HousingBasic>().Where(c => c.UUID == houseUUID).First();
            if(house==null)
                return 0;
            return house.HouseId;
        }

        /// <summary>
        /// 根据楼栋UUID获取四格楼栋ID
        /// </summary>
        /// <param name="BuildUUID"></param>
        /// <returns></returns>
        protected int GetBuildBySIGE(Guid BuildUUID)
        {
            var building = db.Queryable<Building>().Where(c => c.UUID == BuildUUID.ToString()).First();
            return building.BuildId;
        }

        /// <summary>
        ///  根据单元UUID获取四格单元ID
        /// </summary>
        /// <param name="UnitUUID"></param>
        /// <returns></returns>
        protected int GetUnitBySIGE(Guid UnitUUID)
        {
            var unit = db.Queryable<Unit>().Where(c => c.UUID == UnitUUID.ToString()).First();
            return unit.unitId;
        }

        /// <summary>
        /// 根据楼层uuid获取四格id
        /// </summary>
        /// <param name="UnitUUID"></param>
        /// <returns></returns>
        protected int GetFloorBySIGE(string FloorUUID)
        {
            var floor = db.Queryable<Floor>().Where(c => c.UUID == FloorUUID.ToString()).First();
            return floor.FloorId;
        }

        // 当前用户的 UUID，延迟获取
        protected static Guid UserUUID
        {
            get
            {
                // 通过服务定位器获取 IHttpContextAccessor
                var httpContextAccessor = ServiceLocator.GetService<IHttpContextAccessor>();

                var httpContext = httpContextAccessor.HttpContext;
                return httpContext == null
                    ? throw new InvalidOperationException("HTTP context is not available.")
                    : Guid.Parse(httpContext.Items["Guid"].ToString());
            }
        }
        protected static string UserName
        {
            get
            {
                // 通过服务定位器获取 IHttpContextAccessor
                var httpContextAccessor = ServiceLocator.GetService<IHttpContextAccessor>();

                var httpContext = httpContextAccessor.HttpContext;
                return httpContext == null
                    ? throw new InvalidOperationException("HTTP context is not available.")
                    : httpContext.Items["DisplayName"].ToString();
            }
        }

        protected ResponseModel PageSuccess(int PageNumber = 0, int PageSize = 0, int total = 0, object? data = null)
        {
            res.Code = 200;
            res.Message = "操作成功";
            res.Data = new
            {
                PageSize,
                PageNumber,
                total,
                data
            };
            return res;
        }
        protected ResponseModel Success(object? data = null)
        {
            res.Code = 200;
            res.Message = "操作成功";
            if (data != null)
            {
                res.Data = data;
            }
            return res;
        }
        protected ResponseModel Error(string message, int? code = 500)
        {
            res.Code = code ?? 500;
            res.Message = message;
            return res;
        }

        /// <summary>
        /// 获取附件列表通用方法
        /// </summary>
        /// <param name="businessId"></param>
        /// <returns></returns>
        protected List<string> GetAttachment(Guid businessId)
        {
            return db.Queryable<Attachment>()
                .Where(a => a.BusinessId == businessId && a.Status == Status.Enable)
                .Select(a => a.Url)
                .ToList();
        }

        /// <summary>
        /// 获取附件列表通用方法
        /// </summary>
        /// <param name="businessId"></param>
        /// <returns></returns>
        protected async Task<List<string>> GetAttachmentAsync(Guid businessId)
        {
            return await db.Queryable<Attachment>()
                .Where(a => a.BusinessId == businessId && a.Status == Status.Enable)
                .Select(a => a.Url)
                .ToListAsync();
        }

        /// <summary>
        /// 关联附件通用方法
        /// </summary>
        /// <param name="businessId"></param>
        /// <returns></returns>
        protected Boolean SetAttachment(Guid businessId, List<string> Urls)
        {
            try
            {
                db.BeginTran();
                List<Attachment> attlist = [];
                foreach (var url in Urls)
                {
                    attlist.Add(new()
                    {
                        BusinessId = businessId,
                        Url = url,
                        UpdatedBy = UserUUID
                    });
                }
                db.Insertable(attlist).ExecuteCommand();
                db.CommitTran();
                return true;
            }
            catch (Exception)
            {
                db.RollbackTran();
                throw new MSGException("文件上传失败");
            }
        }

        /// <summary>
        /// 关联附件通用方法
        /// </summary>
        /// <param name="businessId"></param>
        /// <returns></returns>
        protected async Task<Boolean> SetAttachmentAsync(Guid businessId, List<string> Urls)
        {
            try
            {
                await db.BeginTranAsync();
                List<Attachment> attlist = [];
                foreach (var url in Urls)
                {
                    attlist.Add(new()
                    {
                        BusinessId = businessId,
                        Url = url,
                        UpdatedBy = UserUUID
                    });
                }
                await db.Insertable(attlist).ExecuteCommandAsync();
                await db.CommitTranAsync();
                return true;
            }
            catch (Exception)
            {
                await db.RollbackTranAsync();
                throw new MSGException("文件上传失败");
            }
        }
    }
}